<script setup>


import {useStore} from "@/store/store.js";
import {computed, ref} from "vue";
import {Check, Document} from "@element-plus/icons-vue";
import {Delta, Quill, QuillEditor} from "@vueup/vue-quill";
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import ColorDot from "@/components/ColorDot.vue";
import {ElMessage} from "element-plus";
import {post} from "@/net/index.js";

const store = useStore()
const props = defineProps({
  show: Boolean,
  defaultTitle: {
    default: '',
    type: String
  },
  defaultType: {
    default: null,
    type: Number
  },
  defaultText: {
    default: '',
    type: String
  },
  submitButton: {
    default: '发布帖子',
    type: String
  },
  submit: {
    default: (editor, success) => {
      post('/api/forum/createTopic', {
        title: editor.value.title,
        content: editor.value.text,
        type: editor.value.type.id,
      }, () => {
        ElMessage.success('发表成功!')
        success()
      })
    },
    type: Function
  }
})
const editorRef = ref()
const emit = defineEmits(['close', 'success'])
const editor = ref({
  type: null,
  title: '',
  text: '',
})
const initEditor = () => {
  if (props.defaultText)
    editor.value.text = new Delta(JSON.parse(props.defaultText))
  else
    editorRef.value.setContents('', 'user')
  editor.value.type = store.findTypeById(props.defaultType)
  editor.value.title = props.defaultTitle
}

const deltaToText = (delta) => {
  if (!delta.ops) return ''
  let text = ''
  for (let op of delta.ops)
    text += op.insert
  return text.replace(/\s/g, '')
}

const countLength = computed(() => deltaToText(editor.value.text).length)
const editorOptions = {
  modules: {
    toolbar: {
      container: [
        "bold", "italic", "underline", "strike", "clean",
        {color: []}, {'background': []},
        {size: ["small", false, "large", "huge"]},
        {header: [1, 2, 3, 4, 5, 6, false]},
        {list: "ordered"}, {list: "bullet"}, {align: []},
        "blockquote", "code-block", "link",
        {indent: '-1'}, {indent: '+1'}
      ],
    },
  }
}
const submitTopic = () => {
  const text = editor.value.text
  if (text.length === 0) {
    ElMessage.warning('帖子内容不能为空')
    return
  }
  if (text.length > 30000) {
    ElMessage.warning('帖子内容不能超过30000字')
    return
  }
  if (!editor.value.title) {
    ElMessage.warning('请输入帖子标题')
  }
  if (!editor.value.type) {
    ElMessage.warning('请选择帖子类型')
    return
  }
  props.submit(editor, () => emit('success'))
}
</script>

<template>
  <div>
    <el-drawer :model-value="show"
               direction="btt"
               @open="initEditor"
               :close-on-click-modal="false"
               :size="650"
               @close="emit('close')"
    >
      <template #header>
        <div>
          <div style="font-weight: bold">发表帖子</div>
          <div style="font-size: 13px">请您务必遵守相关发帖声明和法侓法规，不要出现不文明、违法的行为！</div>
        </div>
      </template>
      <div style="display: flex;gap:10px">
        <div style="width: 150px">
          <el-select placeholder="请选择主题类型" value-key="id" v-model="editor.type"
                     :disabled="!store.forum.types.length">
            <el-option v-for="item in store.forum.types" :value="item" :label="item.name">
              <div>
                <color-dot :color="item.color"/>
                <span style="margin-left: 10px;">{{ item.name }}</span>
              </div>
            </el-option>
          </el-select>
        </div>
        <div style="flex: 1">
          <el-input placeholder="请输入帖子的标题" maxlength="30" :prefix-icon="Document" v-model="editor.title"/>
        </div>
      </div>
      <div style="margin-top: 10px;color: #4f555b;font-size: 13px">
        <color-dot :color="editor.type ? editor.type.color : '#c6c6c6'"/>
        <span style="margin-left: 5px">{{ editor.type ? editor.type.description : '请先选择帖子类型' }}</span>
      </div>
      <div style="margin-top: 10px;height: 430px;overflow: hidden;border-radius: 5px">
        <quill-editor
            v-model:content="editor.text"
            style="height: calc(100vh - 45px)"
            placeholder="今天要分享些什么好呢..."
            content-type="delta"
            ref="editorRef"
            :options="editorOptions"
        />
      </div>
      <div style="display: flex;margin-top: 10px;justify-content: space-between">
        <div style="color: gray;font-size: 13px">
          当前字数 {{ countLength }}（最大支持30000字）
        </div>
        <div>
          <el-button type="success" :icon="Check" @click="submitTopic()">{{ submitButton }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>

::v-deep(.el-drawer) {
  width: 800px;
  margin: auto;
  border-radius: 10px 10px 0 0;
}

::v-deep(.el-drawer__header) {
  margin: 0
}

::v-deep(.ql-toolbar) {
  border-radius: 0 0 5px 5px;
  border-color: var(--el-border-color);
}

::v-deep(.ql-container) {
  border-radius: 0 0 5px 5px;
  border-color: var(--el-border-color);
}

::v-deep(.ql-editor.ql-blank::before) {
  color: var(--el-text-color-placeholder);
  font-style: normal;
  font-size: 12px;
}

::v-deep(.ql-editor) {
  font-size: 16px;
}
</style>